﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

/// <summary>
/// 公用扩展
/// </summary>
public static class CommonExtend
{
    /// <summary>
    /// 深拷贝（被拷贝对象必须可序列化）
    /// </summary>
    /// <typeparam name="T">被拷贝对象的类型</typeparam>
    /// <param name="source">被拷贝的对象</param>
    /// <returns>拷贝</returns>
    public static T DeepClone<T>(this T source)
    {

        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("被复制的对象必须是可序列化的", "source");
        }

        if (source != null)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                T clonedSource = (T)formatter.Deserialize(stream);
                return clonedSource;
            }
        }
        else
        {
            return default;
        }

    }

}
